<template>
  <el-container>
    <el-header class="header">
        <div class="header-main">
          <h1>企业文档管理系统</h1>
          <div class="login" v-if="!$store.state.auth.isLogined">
            <a href="javascript:;" @click="loginForm = true">登录</a>
          </div>
          <div class="login" v-else>
            {{ $store.state.auth.username }} 
            <el-popover placement="bottom-end" width="70" v-model="adminVisible" trigger="hover">
              <div class="popover-main">
                <a href="javascript:;" class="popover-btn" @click="passWordForm = true">修改密码</a>
                <a href="javascript:;" class="popover-btn" @click="onLogout">退出</a>
              </div>
              <a href="javascript:;" slot="reference"><i class="el-icon-arrow-down"></i></a>
            </el-popover>
          </div>
          <el-dialog title="登录" :visible.sync="loginForm" :close-on-click-modal="false" width="500px">
            <el-form>
              <el-form-item label="用户名" :label-width="formLabelWidth">
                <el-input v-model="name" autocomplete="off" autofocus></el-input>
              </el-form-item>
              <el-form-item label="密码" :label-width="formLabelWidth" @keyup.enter.native="onLogin">
                <el-input v-model="password" autocomplete="off" type="password"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="loginForm = false">取 消</el-button>
              <el-button type="primary" @click="onLogin">确 定</el-button>
            </div>
          </el-dialog>
          <el-dialog title="修改密码" :visible.sync="passWordForm" :close-on-click-modal="false" width="500px">
            <el-form>
              <el-form-item label="原密码" :label-width="formLabelWidth">
                <el-input v-model="old_password" autocomplete="off" type="password" autofocus></el-input>
              </el-form-item>
              <el-form-item label="新密码" :label-width="formLabelWidth">
                <el-input v-model="new_password" autocomplete="off" type="password"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" :label-width="formLabelWidth">
                <el-input v-model="re_new_password" autocomplete="off" type="password" @keyup.enter.native="changePassWord"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="passWordForm = false">取 消</el-button>
              <el-button type="primary" @click="changePassWord">确 定</el-button>
            </div>
          </el-dialog>
          <div class="search-main">
            <el-row>
              <el-col :span="17" style="height: 45px;">
                <el-input placeholder="搜索文件" v-model="inputSearch" @keyup.enter.native="onSearch" v-if="isSearchInput">
                  <el-button slot="append" icon="el-icon-search" v-on:click="onSearch"></el-button>
                </el-input>
              </el-col>
              <el-col :span="7">
                <a href="javascript:;" @click="isSearchInput = !isSearchInput" style="line-height: 40px; color: #fff; text-decoration: none; font-size: 14px; margin: 0 10px;">文件搜索</a>
              </el-col>
            </el-row>
          </div>
        </div>    
    </el-header>  
    <el-main class="main">
      <uploader :options="uploadOptions" :autoStart="false" class="uploader-main" :file-status-text="statusText" @files-submitted="filesSubmitted" @file-success="fileSuccess" @file-error="fileError" @complete="filesComplete" @file-removed="fileRemoved" ref="upload">
        <uploader-unsupport></uploader-unsupport>
        <uploader-drop>
          <div class="uploader-top" v-if="$route.name != 'searchFiles' && $store.state.auth.isLogined">
          <!-- <div class="uploader-top"> -->
            <div class="uploader-input">
              <uploader-btn>选择文件上传</uploader-btn>
              <uploader-btn :directory="true">选择文件夹上传</uploader-btn>
              <el-input placeholder="请输入要新建的文件夹名称" v-model="inputDir" class="folder-main" @keyup.enter.native="onDir">
                <template slot="prepend"><i class="icon iconfont icon-icon_folder"></i></template>
                <el-button slot="append" icon="el-icon-plus" v-on:click="onDir"></el-button>
              </el-input>
            </div>
            <uploader-list id="uploader-list"></uploader-list>
          </div>   
          <router-view v-bind:class="{fileloading: isLoading }"></router-view>
        </uploader-drop>
      </uploader>
    </el-main>
    <el-footer class="footer">
      <p>©2015 by Wimanu Network Technology Co., Ltd. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 武汉为企智造网络科技有限公司</p>
    </el-footer>
  </el-container>

</template>

<!--<style>
#uploader-list > ul  > li  > .uploader-file  > .uploader-file-info  > .uploader-file-actions  > .uploader-file-pause,
#uploader-list  > ul  > li  > .uploader-file  > .uploader-file-info  > .uploader-file-actions  > .uploader-file-resume,
#uploader-list  > ul  > li  > .uploader-file  > .uploader-file-info  > .uploader-file-actions  > .uploader-file-retry,
#uploader-list  > ul  > li  > .uploader-file  > .uploader-file-info  > .uploader-file-actions  > .uploader-file-remove {
  display: none;
}
#uploader-list  > ul  > li:first-child > .uploader-file  > .uploader-file-info  > .uploader-file-status > span {
  display: none;
}
#uploader-list  > ul  > li:first-child > .uploader-file  > .uploader-file-info  > .uploader-file-status::before {
  content: '上传中';
}
</style>-->

<script lang="ts">
import { Vue, Component, Watch } from "vue-property-decorator";

@Component
export default class App extends Vue {
  loginForm = false;
  adminVisible = false;
  passWordForm = false;
  isLoading = false;

  formLabelWidth = "70px";

  isSearchInput = false;

  inputDir = "";
  onDir() {
    let dirId = this.$route.params.id;
    let dirName = this.inputDir;
    this.$store
      .dispatch("createDirPromise", { parentId: dirId, name: dirName })
      .then(response => {
        this.$message({
          type: "success",
          message: "目录创建成功!"
        });
        this.$store.dispatch("getFilesAsync", {
          parentId: this.$route.params.id
        });
      })
      .catch(error => {
        this.$message({
          type: "error",
          message: "目录创建成功失败!"
        });
      });
  }

  uploadOptions = {
    target: "/api/Files",
    headers: { Authorization: "" },
    query: { parent_id: 0 },
    chunkSize: 512 * 1024 * 1024,
    simultaneousUploads: 1,
    testChunks: false
  };

  statusText = {
    success: "上传成功",
    error: "上传出错",
    uploading: "上传中",
    paused: "暂停中",
    waiting: "等待中"
  };

  //扫描枪，RFID输入
  searchQrCode = '';
  scanInput(e: KeyboardEvent) {

    if (e.key != "Shift" && e.key != "ArrowDown" && e.key != "Enter") {
      this.searchQrCode += e.key;
    }

    if (e.which === 13) {
      
      this.$store.dispatch("searchScanCodeAsync", {
        code: this.searchQrCode
      }).then(()=>{
        this.$message({
            type: "success",
            message: '搜索：' + this.$store.state.searchFiles.typeCode
        });
        let _this = this;
        setTimeout(function() {
          let search = _this.$store.state.searchFiles.typeCode.split('/')[1];
          _this.$router.push({ name: "searchFiles", params: { search } });
        }, 500);
      });

      this.searchQrCode = '';
    }
   
  }

  mounted() {
    window.addEventListener("keydown", this.scanInput);
    this.$store.dispatch("checkLoginAsync");
  }

  filesSubmitted(files: any, fileList: any[], event: any) {
    // console.log(fileList);
    let upload = this.$refs.upload as any;
    upload.uploader.opts.headers.Authorization = `Bearer ${
      this.$store.state.auth.token
    }`;
    upload.uploader.opts.query.parent_id = this.$route.params.id;
    upload.uploader.resume();
    this.isLoading = true;
    // this.batchUpdate(this.$route.params.id, fileList);
  }

  filesComplete() {
    this.isLoading = false;
  }

  fileRemoved (files: any) {
    let upload = this.$refs.upload as any;
    if (upload.fileList.length == 0) {
      this.isLoading = false;
    }
  }

  // batchUpdate(parentId: string, fileList: any[]) {
  //   let upload = this.$refs.upload as any;
  //   upload.uploader.opts.headers.Authorization = `Bearer ${
  //     this.$store.state.auth.token
  //   }`;
  //   upload.uploader.opts.parent_id = this.$route.params.id;
  //   fileList.map(uploaderFile => {
  //     if (uploaderFile.isFolder) {
  //       // console.log(this)
  //       this.$store
  //         .dispatch("createDirPromise", {
  //           parentId: parentId,
  //           name: uploaderFile.name
  //         })
  //         .then(response => {
  //           let dirId = response.data;
  //           if (dirId > 0) {
  //             this.batchUpdate(dirId, uploaderFile.fileList);
  //           }
  //         })
  //         .catch(error => {
  //           this.$confirm(
  //             "目录已经存在。如需上传，将上传此目录的文件到原目录。",
  //             "提示",
  //             {
  //               confirmButtonText: "确定",
  //               cancelButtonText: "取消",
  //               type: "warning",
  //               center: true
  //             }
  //           )
  //             .then(() => {
  //               let dirId = error.response.data.split("|")[0];
  //               this.batchUpdate(dirId, uploaderFile.fileList);
  //             })
  //             .catch(() => {
  //               this.$message({
  //                 type: "info",
  //                 message: "取消上传!"
  //               });
  //             });
  //         });
  //     } else {
  //       this.$store.dispatch('createFilePromise', {
  //         parentId: parentId,
  //         file: uploaderFile.file
  //       }).then(response => {
  //         uploaderFile.cancel();
  //         this.$store.dispatch("getFilesAsync", { parentId: this.$route.params.id });
  //       }).catch(error => {
  //         this.$message({
  //           type: "error",
  //           message: error.response.data.split("|")[1]
  //         });
  //         uploaderFile.cancel();
  //       })
  //     }
  //   });
  // }

  fileSuccess(rootFile: any, file: any, message: any, chunk: any) {
    let upload = this.$refs.upload as any;
    this.$store.dispatch("getFilesAsync", { parentId: this.$route.params.id });
    setTimeout(function() {
      upload.uploader.removeFile(file);
    }, 1000);
  }

  fileError(rootFile: any, file: any, message: any, chunk: any) {
    let upload = this.$refs.upload as any;
    if (message) {
      let fileId = message.split("|")[0];
      let tips = message.split("|")[1] + "如需上传，将覆盖原有文件。";
      this.$confirm(tips, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          this.$store
            .dispatch("deleteFile", { id: fileId })
            .then(response => {
              upload.uploader.retry();
              this.$store.dispatch("getFilesAsync", {
                parentId: this.$route.params.id
              });
            })
            .catch(error => {
              this.$message({
                type: "error",
                message: "上传失败！"
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消上传此文件"
          });
          setTimeout(function() {
            upload.uploader.removeFile(file);
          }, 1000);
        });
    }
  }

  inputSearch = "";
  onSearch() {
    let search = this.inputSearch;
    this.$router.push({ name: "searchFiles", params: { search } });
  }

  name = "";
  password = "";
  onLogin() {
    this.$store.dispatch("loginAsync", {
      name: this.name,
      password: this.password
    });
    this.loginForm = false;
    let upload = this.$refs.upload as any;
    upload.uploader.cancel();
  }

  onLogout() {
    this.$store.commit("logout");
  }

  old_password = "";
  new_password = "";
  re_new_password = "";
  changePassWord() {
    this.$store
      .dispatch("changePasswordPromise", {
        password: this.old_password,
        newPassword: this.new_password,
        reNewPassword: this.re_new_password
      })
      .then(resp => {
        console.log(resp);
        if (resp.data > 0) {
          this.$message({
            type: "success",
            message: "密码修改成功！"
          });
        } else {
          this.$message({
            type: "error",
            message: "原密码输入错误！"
          });
        }
      })
      .catch(error => {
        this.$message({
          type: "error",
          message: error.response.data
        });
      });
    this.passWordForm = false;
  }
}
</script>
